package org.budo.launcher.netty.servlet;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.ServletRegistration.Dynamic;

import org.budo.launcher.service.config.AbstractWebXmlConfigParser;
import org.budo.launcher.service.config.FilterConf;
import org.budo.launcher.service.config.FilterMappingConf;
import org.budo.launcher.service.config.ServletConf;
import org.budo.netty.servlet.server.DefaultBudoServletServer;

/**
 * @author lmw
 */
public class BudoNettyServletWebXmlConfigParser extends AbstractWebXmlConfigParser {
    private DefaultBudoServletServer budoNettyServletServer;

    public BudoNettyServletWebXmlConfigParser(DefaultBudoServletServer budoNettyServletServer) {
        this.budoNettyServletServer = budoNettyServletServer;
    }

    @Override
    public void addContextParam(String paramName, String paramValue) {
        budoNettyServletServer.getServletContext() //
                .setInitParameter(paramName, paramValue);
    }

    @Override
    public void addListener(String listenerClass) {
        budoNettyServletServer.getServletContext() //
                .addListener(listenerClass);
    }

    @Override
    public void addFilter(FilterConf filterConf) {
        budoNettyServletServer.getServletContext() //
                .addFilter(filterConf.getFilterName(), filterConf.getFilterClass()) //
                .setInitParameters(filterConf.getInitParamMap());
    }

    @Override
    public void addFilterUrlMapping(FilterMappingConf filterMappingConf) {
        EnumSet<DispatcherType> dispatcherTypes = this.getDispatcherTypeEnumSet(filterMappingConf);

        budoNettyServletServer.getServletContext().getFilterRegistration(filterMappingConf.getFilterName()) //
                .addMappingForUrlPatterns(dispatcherTypes, true, filterMappingConf.getUrlPatternList().toArray(new String[0]));
    }

    @Override
    public void addServlet(ServletConf servletConf) {
        Dynamic dynamic = budoNettyServletServer.getServletContext() //
                .addServlet(servletConf.getServletName(), servletConf.getServletClass().getName());

        dynamic.addMapping(servletConf.getUrlPattern());
        dynamic.setInitParameters(servletConf.getInitParamMap());

        Integer loadOnStartup = servletConf.getLoadOnStartup();
        if (null != loadOnStartup) {
            dynamic.setLoadOnStartup(loadOnStartup);
        }
    }

    @Override
    public void addWelcomePage(String welcomePage) {
        budoNettyServletServer.getWelcomeFileList().add(welcomePage);
    }

    @Override
    public void addErrorPage(String location, Integer errorCode) {}
}